import QtQuick 2.15
import QtQuick.Layouts 1.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
import FluentUI 1.0
import "../comp"

FluContentPage {
    id: root

    // 当前选中的组织ID
    property string currentOrgId: ""
    property var selectedMap: ({})
    property bool allSelected: false
    property bool isdelete: false
    // 刷新树形结构数据
    function refreshTree() {
        org_tree_view.dataSource = orgService.tree()
    }

    // 加载表格数据
    function loadTableData() {
        var params = {
            "current": pagination.pageCurrent,
            "size": pagination.__itemPerPage,
            "parentId": org_tree_view.current ? org_tree_view.current.data.id : "0",
            "searchKey": nameSearchInput.text
        }
        root.selectedMap = ({})
        var result = orgService.page(params)
        table_view.dataSource = result.records
        pagination.itemCount = result.total

        // 重置全选状态
        root.allSelected = false

        // 更新选中状态
        updateSelectedState()
    }

    // 更新选中ID列表
    function updateSelectedState() {
        // 检查是否有记录
        if (table_view.dataSource.length === 0) {
            root.allSelected = false
            return
        }

        var allChecked = true
        for (var i = 0; i < table_view.dataSource.length; i++) {
            var record = table_view.dataSource[i]
            var isSelected = root.selectedMap[record.id] || false
            if (!isSelected) {
                allChecked = false
            }
        }
        root.allSelected = allChecked
    }

    // 切换单个记录的选中状态
    function toggleRecordSelection(id) {
        // 切换选中状态
        root.selectedMap[id] = !root.selectedMap[id]
        updateSelectedState()
    }

    function getSelectedIds() {
        var ids = []
        for (var id in root.selectedMap) {
            if (root.selectedMap[id]) {
                ids.push(id)
            }
        }
        return ids
    }

    // 切换所有记录的选中状态
    function toggleAllSelection() {
        // 如果没有记录，直接返回
        if (table_view.dataSource.length === 0) {
            root.allSelected = false
            return
        }

        var newState = !root.allSelected

        // 更新当前页所有记录的选中状态
        for (var i = 0; i < table_view.dataSource.length; i++) {
            var record = table_view.dataSource[i]
            root.selectedMap[record.id] = newState
        }
        root.allSelected = newState
        table_view.dataSourceChanged()
    }

    // 删除记录函数
    function deleteRecord(id) {
        var success = orgService.deleteById(id)
        if (success) {
            showSuccess(qsTr("删除成功"))
            loadTableData()
            refreshTree()
        } else {
            showError(qsTr("删除失败"), 3000)
        }
    }

    Component.onCompleted: {
        loadTableData()
    }

    EnhancedDialog {
        id: dialog_delete
        title: qsTr("确认删除")
        message: qsTr("确定要删除选中记录吗？")
        buttonFlags: FluContentDialogType.NegativeButton | FluContentDialogType.PositiveButton
        positiveText: qsTr("确定")
        negativeText: qsTr("取消")
        onClosed: {
            if (result === EnhancedDialog.PositiveClicked) {
                isdelete = true
                // 执行删除操作
            } else {
                isdelete = false
            }
        }
    }
    // 列头复选框组件
    Component {
        id: com_header_checkbox
        Item {
            property bool isChecked: root.allSelected
            FluCheckBox {
                id: headerCheckbox
                anchors.centerIn: parent
                checked: parent.isChecked
                enabled: table_view.dataSource.length > 0
                animationEnabled: false
                onClicked: {
                    root.toggleAllSelection()
                }
            }
            onIsCheckedChanged: {
                headerCheckbox.checked = isChecked
            }
        }
    }

    // 复选框组件
    Component {
        id: com_checkbox
        Item {
            FluCheckBox {
                anchors.centerIn: parent
                checked: root.selectedMap[rowModel.id] || false
                animationEnabled: false
                onClicked: {
                    root.toggleRecordSelection(rowModel.id)
                }
            }
        }
    }

    // 分类显示组件
    Component {
        id: com_category
        Item {
            FluText {
                anchors.centerIn: parent
                text: {
                    if (rowModel.category === "COMPANY")
                        return qsTr("公司")
                    if (rowModel.category === "DEPT")
                        return qsTr("部门")
                    return qsTr("未知")
                }
            }
        }
    }

    // 操作列组件
    Component {
        id: com_action
        Item {
            RowLayout {
                anchors.centerIn: parent
                spacing: 5

                FluFilledButton {
                    text: qsTr("编辑")
                    Layout.preferredWidth: 60
                    onClicked: {
                        console.log("编辑记录:", rowModel.id)
                        // 这里添加编辑逻辑
                    }
                }

                FluButton {
                    text: qsTr("删除")
                    Layout.preferredWidth: 60
                    onClicked: {
                        dialog_delete.openWithCallback(function (result) {
                            if (result === EnhancedDialog.PositiveClicked) {
                                root.deleteRecord(rowModel.id)
                            }
                        })
                    }
                }
            }
        }
    }

    RowLayout {
        anchors.fill: parent
        spacing: 0

        // 左侧导航
        EnhancedTreeView {
            id: org_tree_view
            Layout.preferredWidth: 260
            Layout.minimumWidth: 200
            Layout.maximumWidth: 300
            Layout.fillHeight: true
            cellHeight: 30
            showLine: false
            checkable: false
            depthPadding: 20
            onCurrentChanged: {
                loadTableData()
            }
            columnSource: [{
                    "title": qsTr("机构"),
                    "dataIndex": "name",
                    "width": width
                }]
            Component.onCompleted: {
                dataSource = orgService.tree()
            }
        }

        // 分隔线
        Rectangle {
            width: 6
            Layout.fillHeight: true
            color: FluTheme.dividerColor
        }

        // 右侧内容
        ColumnLayout {
            id: contentArea
            Layout.fillWidth: true
            Layout.fillHeight: true
            spacing: 0

            // ===== 顶部搜索区域 =====
            FluRectangle {
                id: searchBar
                Layout.fillWidth: true
                Layout.preferredHeight: 50
                color: "transparent"
                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: 5
                    spacing: 8

                    // 搜索表单
                    RowLayout {
                        spacing: 15
                        // 搜索标题
                        FluText {
                            text: qsTr("名称关键词:")
                            font.bold: true
                            font.pixelSize: 14
                        }

                        // 名称关键词输入框
                        FluTextBox {
                            id: nameSearchInput
                            placeholderText: qsTr("输入组织名称关键词")
                            Layout.preferredWidth: 200
                            Layout.preferredHeight: 36
                        }

                        // 查询按钮
                        FluFilledButton {
                            id: searchButton
                            text: qsTr("查询")
                            Layout.preferredWidth: 80
                            Layout.preferredHeight: 36
                            onClicked: {
                                pagination.pageCurrent = 1
                                loadTableData()
                            }
                        }

                        // 重置按钮
                        FluButton {
                            id: resetButton
                            text: qsTr("重置")
                            Layout.preferredWidth: 80
                            Layout.preferredHeight: 36
                            onClicked: {
                                nameSearchInput.text = ""
                                pagination.pageCurrent = 1
                                loadTableData()
                            }
                        }
                    }
                }
            }

            // 搜索栏与表格之间的分隔线
            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: 5
                color: FluTheme.dividerColor
            }

            FluFrame {
                id: layout_controls
                Layout.fillWidth: true
                Layout.preferredHeight: 40
                clip: true
                Row {
                    spacing: 12
                    anchors {
                        left: parent.left
                        leftMargin: 10
                        verticalCenter: parent.verticalCenter
                    }
                    FluFilledButton {
                        id: addButton
                        text: qsTr("新增")
                        width: 72
                        onClicked: {

                        }
                    }
                    // 批量删除按钮
                    FluButton {
                        text: qsTr("批量删除")
                        onClicked: {
                            var selectedIds = root.getSelectedIds()
                            if (selectedIds.length === 0) {
                                showWarning(qsTr("请先选择要删除的记录"))
                                return
                            }
                            dialog_delete.openWithCallback(function (result) {
                                if (result === EnhancedDialog.PositiveClicked) {
                                    // 批量删除所有选中ID
                                    var deletedCount = orgService.deleteByIds(selectedIds)

                                    if (deletedCount > 0) {
                                        showSuccess(qsTr("成功删除 %1 条记录").arg(deletedCount))
                                        loadTableData()
                                        refreshTree()
                                    } else {
                                        showError(qsTr("删除失败，请重试"))
                                    }
                                }
                            })
                        }
                    }
                }
            }
            // ===== 中间表格区域 =====
            EnhancedTableView {
                id: table_view
                Layout.fillWidth: true
                Layout.fillHeight: true
                Layout.minimumHeight: 200
                anchors.topMargin: 5
                rowHeight: 32
                editable: false
                // 在数据模型中添加checked属性
                onDataSourceChanged: {
                    if (!dataSource)
                        return
                    root.updateSelectedState()
                }

                columnSource: [{
                        "title": table_view.customItem(com_header_checkbox),
                        "dataIndex": "id",
                        "frozen": true,
                        "width": 60,
                        "readonly": true,
                        "itemDelegate": com_checkbox
                    }, {
                        "title": qsTr("组织名称"),
                        "dataIndex": "name",
                        "readonly": true,
                        "width": 200,
                        "minimumWidth": 100,
                        "maximumWidth": 300
                    }, {
                        "title": qsTr("分类"),
                        "dataIndex": "category",
                        "readonly": true,
                        "width": 100,
                        "minimumWidth": 80,
                        "maximumWidth": 200,
                        "itemDelegate": com_category
                    }, {
                        "title": qsTr("排序"),
                        "dataIndex": "sortCode",
                        "readonly": true,
                        "width": 80,
                        "minimumWidth": 80,
                        "maximumWidth": 100
                    }, {
                        "title": qsTr("操作"),
                        "dataIndex": "action",
                        "width": 160,
                        "frozen": true,
                        "itemDelegate": com_action
                    }]
            }
            RowLayout {
                Layout.fillWidth: true
                Layout.preferredHeight: 60
                Item {
                    Layout.fillWidth: true
                }
                EnhancedPagination {
                    id: pagination
                    Layout.alignment: Qt.AlignLeft
                    pageCurrent: 1
                    itemCount: 100
                    pageButtonCount: 7
                    __itemPerPage: 10
                    previousText: qsTr("<上一页")
                    nextText: qsTr("下一页>")

                    onRequestPage: (page, count) => {
                                       table_view.closeEditor()
                                       loadTableData()
                                       table_view.resetPosition()
                                   }
                }
            }
        }
    }
}
